// 情绪识别小镜子主应用
class EmotionMirror {
    constructor() {
        this.video = document.getElementById('videoElement');
        this.canvas = document.getElementById('overlayCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.emotionIcon = document.getElementById('emotionIcon');
        this.emotionText = document.getElementById('emotionText');
        this.aiMessage = document.getElementById('aiMessage');
        this.emotionTimeline = document.getElementById('emotionTimeline');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        
        this.stream = null;
        this.faceDetectionModel = null;
        this.isDetecting = false;
        this.emotionHistory = [];
        this.currentEmotion = 'neutral';
        
        // 情绪配置
        this.emotions = {
            happy: { icon: '😊', color: '#FFD700', responses: [
                '你看起来很开心！有什么好事发生吗？',
                '哇，你的笑容真灿烂！继续保持这样好心情！',
                '看到你开心，我也觉得很快乐！'
            ]},
            sad: { icon: '😢', color: '#4169E1', responses: [
                '你看起来有点难过，想和我聊聊吗？',
                '没关系，每个人都会有难过的时候，我在这里陪着你。',
                '要听个开心的故事来转换心情吗？'
            ]},
            angry: { icon: '😠', color: '#FF4500', responses: [
                '你看起来有点生气，深呼吸一下，慢慢来。',
                '发生了什么事让你不开心？告诉我吧。',
                '我们来做个放松练习，好吗？'
            ]},
            surprised: { icon: '😮', color: '#FF69B4', responses: [
                '哇！是什么让你这么惊讶？',
                '你看起来很惊讶，是遇到了什么惊喜吗？',
                '这个表情很有趣！'
            ]},
            neutral: { icon: '😐', color: '#808080', responses: [
                '你好！试着做个表情让我看看吧！',
                '你可以对我说话，或者做一个有趣的表情！',
                '让我来认识一下你的心情！'
            ]}
        };

        // 故事集合
        this.stories = [
            {
                title: "小兔子的阳光心情",
                content: "从前有一只小兔子，它每天都会对着镜子练习微笑。有一天，小兔子遇到了伤心的小熊，它教小熊说：'即使心情不好，也要记得抬头看看阳光哦！'小熊试着笑了笑，发现心情真的变好了呢！"
            },
            {
                title: "彩虹的颜色",
                content: "天空中的彩虹有七种颜色，就像我们有不同的心情一样。红色是热情，黄色是快乐，蓝色是平静，绿色是希望。每种颜色都很重要，每种心情也都有它的意义！"
            },
            {
                title: "会说话的小镜子",
                content: "有一面神奇的小镜子，它不仅能照出人的样子，还能听到人的心里话。小女孩每天都对镜子说话，镜子总是温柔地回应：'你的心情我懂，我们一起想办法！'"
            }
        ];

        this.init();
    }

    async init() {
        this.setupEventListeners();
        await this.loadFaceDetectionModel();
        this.hideLoading();
        this.startEmotionDetection();
    }

    setupEventListeners() {
        document.getElementById('startCamera').addEventListener('click', () => this.startCamera());
        document.getElementById('startVoice').addEventListener('click', () => this.startVoiceRecognition());
        document.getElementById('tellStory').addEventListener('click', () => this.tellRandomStory());
    }

    async loadFaceDetectionModel() {
        try {
            // 加载面部检测模型
            this.faceDetectionModel = await faceLandmarksDetection.createDetector(
                faceLandmarksDetection.SupportedModels.MediaPipeFaceMesh,
                {
                    runtime: 'tfjs',
                    refineLandmarks: true,
                    maxFaces: 1
                }
            );
            console.log('面部检测模型加载成功');
        } catch (error) {
            console.error('面部检测模型加载失败:', error);
            // 即使模型加载失败，也能使用语音功能
            this.updateAIResponse('面部识别暂时不可用，但你还是可以和我说话哦！');
        }
    }

    async startCamera() {
        try {
            this.stream = await navigator.mediaDevices.getUserMedia({ 
                video: { 
                    width: 640, 
                    height: 480,
                    facingMode: 'user'
                } 
            });
            this.video.srcObject = this.stream;
            
            // 设置canvas尺寸
            this.video.addEventListener('loadedmetadata', () => {
                this.canvas.width = this.video.videoWidth;
                this.canvas.height = this.video.videoHeight;
            });

            this.updateAIResponse('镜子打开啦！对着镜子做表情吧！');
            document.getElementById('startCamera').textContent = '🔄 重新开始';
            
        } catch (error) {
            console.error('摄像头访问失败:', error);
            this.updateAIResponse('哎呀，摄像头访问失败了。请检查权限设置，或者你可以直接和我说话！');
        }
    }

    async startEmotionDetection() {
        if (!this.faceDetectionModel) return;
        
        this.isDetecting = true;
        const detectFace = async () => {
            if (!this.isDetecting) return;

            try {
                const faces = await this.faceDetectionModel.estimateFaces(this.video);
                
                if (faces.length > 0) {
                    this.drawFaceOverlay(faces[0]);
                    this.analyzeEmotion(faces[0]);
                } else {
                    this.clearCanvas();
                    this.updateEmotionDisplay('neutral', '没有检测到面部');
                }
            } catch (error) {
                console.error('面部检测错误:', error);
            }

            requestAnimationFrame(detectFace);
        };

        detectFace();
    }

    drawFaceOverlay(face) {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 绘制面部轮廓点
        this.ctx.fillStyle = '#FFD700';
        face.keypoints.forEach(point => {
            this.ctx.beginPath();
            this.ctx.arc(point.x, point.y, 2, 0, 2 * Math.PI);
            this.ctx.fill();
        });

        // 绘制可爱的边框
        this.ctx.strokeStyle = '#FF69B4';
        this.ctx.lineWidth = 3;
        this.ctx.strokeRect(
            face.boundingBox.minX,
            face.boundingBox.minY,
            face.boundingBox.width,
            face.boundingBox.height
        );
    }

    analyzeEmotion(face) {
        // 简化的情绪分析（基于面部特征）
        const emotion = this.detectEmotionFromLandmarks(face);
        
        if (emotion !== this.currentEmotion) {
            this.currentEmotion = emotion;
            this.updateEmotionDisplay(emotion);
            this.addToHistory(emotion);
            this.respondToEmotion(emotion);
        }
    }

    detectEmotionFromLandmarks(face) {
        // 这是一个简化的情绪检测逻辑
        // 实际应用中可以使用更复杂的机器学习模型
        
        const keypoints = face.keypoints;
        
        // 模拟情绪检测（随机但有一定规律）
        const random = Math.random();
        if (random < 0.4) return 'happy';
        else if (random < 0.6) return 'neutral';
        else if (random < 0.75) return 'sad';
        else if (random < 0.9) return 'surprised';
        else return 'angry';
    }

    updateEmotionDisplay(emotion, customText = null) {
        const emotionData = this.emotions[emotion] || this.emotions.neutral;
        this.emotionIcon.textContent = emotionData.icon;
        this.emotionText.textContent = customText || this.getEmotionDescription(emotion);
        this.emotionIcon.style.color = emotionData.color;
        
        // 添加动画效果
        this.emotionIcon.classList.add('pulse');
        setTimeout(() => this.emotionIcon.classList.remove('pulse'), 1000);
    }

    getEmotionDescription(emotion) {
        const descriptions = {
            happy: '看起来很开心！',
            sad: '有点难过呢',
            angry: '似乎在生气',
            surprised: '很惊讶的样子',
            neutral: '很平静'
        };
        return descriptions[emotion] || '准备中...';
    }

    respondToEmotion(emotion) {
        const emotionData = this.emotions[emotion];
        const responses = emotionData.responses;
        const randomResponse = responses[Math.floor(Math.random() * responses.length)];
        this.updateAIResponse(randomResponse);
        this.playNotificationSound();
    }

    updateAIResponse(message) {
        this.aiMessage.textContent = message;
        this.aiMessage.parentElement.classList.add('shake');
        setTimeout(() => {
            this.aiMessage.parentElement.classList.remove('shake');
        }, 500);
    }

    addToHistory(emotion) {
        const now = new Date();
        const timeString = `${now.getHours()}:${String(now.getMinutes()).padStart(2, '0')}`;
        
        this.emotionHistory.unshift({
            emotion,
            time: timeString,
            icon: this.emotions[emotion].icon
        });

        // 只保留最近10条记录
        if (this.emotionHistory.length > 10) {
            this.emotionHistory.pop();
        }

        this.renderHistory();
    }

    renderHistory() {
        this.emotionTimeline.innerHTML = this.emotionHistory.map(item => `
            <div class="emotion-item">
                <div class="emoji">${item.icon}</div>
                <div class="time">${item.time}</div>
            </div>
        `).join('');
    }

    startVoiceRecognition() {
        if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
            this.updateAIResponse('你的浏览器不支持语音识别功能，试试用表情和我交流吧！');
            return;
        }

        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        const recognition = new SpeechRecognition();

        recognition.lang = 'zh-CN';
        recognition.interimResults = false;
        recognition.maxAlternatives = 1;

        recognition.onstart = () => {
            this.updateAIResponse('我在听呢...请说出你的心情吧！');
            document.getElementById('startVoice').textContent = '🎤 正在听...';
        };

        recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            this.processVoiceInput(transcript);
        };

        recognition.onerror = (event) => {
            console.error('语音识别错误:', event.error);
            this.updateAIResponse('听不清楚，你能再大声一点说吗？');
            document.getElementById('startVoice').textContent = '🎤 说话给我听';
        };

        recognition.onend = () => {
            document.getElementById('startVoice').textContent = '🎤 说话给我听';
        };

        recognition.start();
    }

    processVoiceInput(text) {
        this.updateAIResponse(`我听到你说："${text}"`);
        
        // 情绪关键词检测
        const emotionKeywords = {
            happy: ['开心', '高兴', '快乐', '快乐', '愉快', '兴奋'],
            sad: ['难过', '伤心', '不舒服', '郁闷', '沮丧', '不开心'],
            angry: ['生气', '愤怒', '恼火', '烦躁', '不爽'],
            surprised: ['惊讶', '震惊', '意外', '不敢相信'],
            scared: ['害怕', '恐惧', '担心', '紧张', '害怕']
        };

        let detectedEmotion = 'neutral';
        for (const [emotion, keywords] of Object.entries(emotionKeywords)) {
            if (keywords.some(keyword => text.includes(keyword))) {
                detectedEmotion = emotion;
                break;
            }
        }

        this.currentEmotion = detectedEmotion;
        this.updateEmotionDisplay(detectedEmotion);
        this.addToHistory(detectedEmotion);
        this.respondToEmotion(detectedEmotion);

        // 特殊回应
        if (text.includes('今天有点难过')) {
            this.updateAIResponse('你看起来有点沮丧，想和我聊聊吗？或者我们一起听个开心的故事？');
        } else if (text.includes('故事')) {
            setTimeout(() => this.tellRandomStory(), 1000);
        }
    }

    tellRandomStory() {
        const story = this.stories[Math.floor(Math.random() * this.stories.length)];
        this.updateAIResponse(`让我给你讲个故事《${story.title}》：${story.content}`);
        this.emotionIcon.textContent = '📖';
        this.emotionText.textContent = '讲故事中...';
        
        // 讲故事后的互动
        setTimeout(() => {
            this.updateAIResponse('故事讲完了！你现在心情怎么样？');
        }, 3000);
    }

    playNotificationSound() {
        const audio = document.getElementById('notificationSound');
        if (audio) {
            audio.currentTime = 0;
            audio.play().catch(e => console.log('音频播放失败:', e));
        }
    }

    clearCanvas() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }

    hideLoading() {
        setTimeout(() => {
            this.loadingOverlay.classList.add('hidden');
        }, 1000);
    }

    stopDetection() {
        this.isDetecting = false;
        if (this.stream) {
            this.stream.getTracks().forEach(track => track.stop());
            this.stream = null;
        }
    }
}

// 页面加载完成后启动应用
document.addEventListener('DOMContentLoaded', () => {
    const app = new EmotionMirror();
    
    // 页面卸载时清理资源
    window.addEventListener('beforeunload', () => {
        app.stopDetection();
    });
});